# -*- coding: utf-8 -*-
from __future__ import absolute_import

import datetime
import os
import time

import oss2
from celery import Celery
from celery.utils.log import get_task_logger


# from .init_celery import celery

# mqTool = RabbitMQTool(host = '192.168.0.xx',
# 						vhost = 'vhost_walker',
# 						queue = 'queue_walker',
# 						user = 'walker',
# 						passwd = 'walker')

def writetxt(file, text):
    file_object = open(os.getcwd() + "/chatterbot/" + file + "/" + time.strftime("%Y-%m-%d") + ".txt", "a")
    try:
        file_object.write("" + text + "\n")
    finally:
        file_object.close()


# 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
# 172.17.6.149   179
auth = oss2.Auth('LTAIHp9ZwJFOGy2f', '22MjTZT3DHTINmFaawEM6NJUDO9dUn')
bucket = oss2.Bucket(auth, 'http://oss-cn-beijing-internal.aliyuncs.com', 'zvoice')
app = Celery('Celeryupfile', backend='amqp://lzj:Haitang110@172.17.6.149:5672//',
             broker='amqp://lzj:Haitang110@172.17.6.149:5672//',
             CELERY_ROUTES={
                 'worker.file47': {'queue': 'file47'},
                 'worker.file179': {'queue': 'file179'},
                 'worker.file132': {'queue': 'file132'},
             },

             CELERY_TASK_RESULT_EXPIRES=20,  # 任务结果有限时间
             # CELERY_SEND_TASK_ERROR_EMAILS = True,  #f发送错误邮件
             # ADMINS = (''),
             # CELERYD_PREFETCH_MULTIPLIER=1  #worker每次从Rabbitmq一次性取走多的消息数
             acks_late=True,  # task被执行完成之后，才会向队列发送 acknowledged 。
             heartbeat_interval=0,
             )

log = get_task_logger(__name__)


# app.conf.update(
#     result_expires=3600,   #任务结果保存时间
# )
# Celery的CELERY_ACKS_LATE=True，表示Worker在任务执行完后才向Broker发送acks，告诉队列这个任务已经处理了
# ，而不是在接收任务后执行前发送，这样可以在Worker处理任务过程中异常退出，这个任务还会被发送给别的Worker处理。
# 但是可能的情况是，一个任务会被多次执行，所以一定要慎用。
# ,include=['chatterbot.zyrobot.projectsql.robotsql.upfile']
# ignore_result=True
@app.task(name='worker.file179', serializer='json', ignore_result=True, store_errors_even_if_ignored=True)
def upfile(filenewname, filename):
    try:
        log.info("Calling task up(%s, %s)" % (str(filenewname), str(filename)))
        writetxt('filetxt', str(datetime.datetime.now()) + ' ' 'filenamebegin' + ' ' + str(filename))
        bucket.put_object_from_file(filenewname, filename)
        writetxt('filetxt', str(datetime.datetime.now()) + ' ' 'filenameend' + ' ' + str(filename))
        if os.path.isfile(filename):
            os.remove(filename)
            writetxt('filetxt', str(datetime.datetime.now()) + 'delfilenameend' + ' ' + str(filename))
        return 'ture'
    except Exception as e:
        writetxt('filetxt', str(datetime.datetime.now()) + ' ' 'filenameerr' + ' ' + str(e))
        return 'false'
